#include <QDebug>
#include <QPushButton>
#include <QMessageBox>
#include <QSqlQuery>
#include <QSqlError>
#include "taskeditdialog.h"
#include "ui_taskeditdialog.h"
#include "sqlhelper.h"

TaskEditDialog::TaskEditDialog(QWidget *parent, QSqlDatabase db, int userid, const QDateTime& start, const QDateTime& end)
    : QDialog(parent)
    , ui(new Ui::TaskEditDialog)
    , db_(db)
    , companyID_(0)
    , userID_(userid)
    , taskID_(0)
    , prodID_(0)
    , compID_(0)
    , cateID_(0)
{
    ui->setupUi(this);

    initialize(start, end);
    ui->removeTaskButton->setVisible(false);
}

TaskEditDialog::TaskEditDialog(QWidget *parent, QSqlDatabase db, int userid, const CalendarItem& item)
    : QDialog(parent)
    , ui(new Ui::TaskEditDialog)
    , db_(db)
    , companyID_(item.companyID)
    , userID_(userid)
    , taskID_(item.id)
    , prodID_(item.prodID)
    , compID_(item.compID)
    , cateID_(item.cateID)
{
    ui->setupUi(this);

    initialize(item.stime, item.etime, item.comment);
    ui->removeTaskButton->setVisible(true);
}

TaskEditDialog::~TaskEditDialog()
{
    delete ui;
}

void TaskEditDialog::initialize(const QDateTime& start, const QDateTime& end, const QString& comment)
{
    ui->startEdit->setDateTime(start);
    ui->endEdit->setDateTime(end);

    initializeCompanyCombo();
    ui->commentEdit->setPlainText(comment);

    ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(noError());
}

void TaskEditDialog::initializeCompanyCombo()
{
    QSqlQuery query = db_.exec("select id, name from COMPANY");
    while (query.next()) {
        int id = query.value(0).toInt();
        QString name = query.value(1).toString();
        ui->companyComboBox->addItem(name, id);
        if (companyID_ == id)
            ui->companyComboBox->setCurrentIndex(ui->companyComboBox->count()-1);
    }
}

void TaskEditDialog::initializeProductCombo(int companyID)
{
    ui->productComboBox->clear();

    QString q = QString("select P.id, P.name from PRODUCT AS P, CLIENTUSERS as CL, COMPANY AS CO where P.closed=0 and P.clientID=CL.id and CL.companyID=CO.id and CO.id='%1' order by P.sortorder").arg(companyID);
    QSqlQuery query = db_.exec(q);
    while (query.next()) {
        int id = query.value(0).toInt();
        QString name = query.value(1).toString();
        ui->productComboBox->addItem(name, id);
        if (id == prodID_)
            ui->productComboBox->setCurrentIndex(ui->productComboBox->count()-1);
    }
}

void TaskEditDialog::initializeComponentCombo(int productID)
{
    ui->componentComboBox->clear();
    ui->componentComboBox->addItem("", 0);

    QString q = QString("select id, name, japaneseName from COMPONENT where prodid='%1' order by sortorder").arg(productID);
    QSqlQuery query = db_.exec(q);
    while (query.next()) {
        int id = query.value(0).toInt();
        QString name = query.value(1).toString() + "\t" + query.value(2).toString();
        ui->componentComboBox->addItem(name, id);
        if (id == compID_)
            ui->componentComboBox->setCurrentIndex(ui->componentComboBox->count()-1);
    }
}

void TaskEditDialog::initializeCategoryCombo(int productID)
{
    ui->categoryComboBox->clear();

    QString q = QString("select TC.id, TC.name from TASKCATEGORY AS TC, PRODUCTTASK AS PT where PT.prodid='%1' and PT.cateid=TC.id").arg(productID);
    QSqlQuery query = db_.exec(q);
    while (query.next()) {
        int id = query.value(0).toInt();
        QString name = query.value(1).toString();
        ui->categoryComboBox->addItem(name, id);
        if (cateID_ == id)
            ui->categoryComboBox->setCurrentIndex(ui->categoryComboBox->count()-1);
    }
}

void TaskEditDialog::accept()
{
    QDateTime s = ui->startEdit->dateTime();
    QDateTime e = ui->endEdit->dateTime();

    if (SqlHelper().conflictTask(db_, taskID_, userID_, s, e)) {
        QMessageBox::warning(this, QString(), tr("Task is conflicting with other tasks."));
        return;
    }

    QDialog::accept();

    int prodid = ui->productComboBox->itemData(ui->productComboBox->currentIndex()).toInt();
    int cateid = ui->categoryComboBox->itemData(ui->categoryComboBox->currentIndex()).toInt();
    int intcompid = ui->componentComboBox->itemData(ui->componentComboBox->currentIndex()).toInt();
    QString compid = intcompid ? QString("%1").arg(intcompid) : "NULL";

    if (taskID_ > 0) {
        QString q = QString(
                    "UPDATE ACTUAL"
                    " SET startTime='%1', endTime='%2', prodid=%3, compid=%4, cateid=%5, comment='%6'"
                    " WHERE id='%7'")
                .arg(s.toString(Qt::ISODate)).arg(e.toString(Qt::ISODate)).arg(prodid).arg(compid).arg(cateid).arg(ui->commentEdit->toPlainText()).arg(taskID_);
        db_.exec(q);
    }
    else {
        QString q = QString(
                    "INSERT INTO ACTUAL"
                    "(userid, startTime, endTime, prodid, compid, cateid, comment)"
                    " VALUES('%1', '%2', '%3', %4, %5, %6, '%7')")
                .arg(userID_).arg(s.toString(Qt::ISODate)).arg(e.toString(Qt::ISODate)).arg(prodid).arg(compid).arg(cateid).arg(ui->commentEdit->toPlainText());
        db_.exec(q);
    }
}

void TaskEditDialog::on_companyComboBox_currentIndexChanged(int index)
{
    initializeProductCombo( ui->companyComboBox->itemData(index).toInt() );

    ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(noError());
}

void TaskEditDialog::on_productComboBox_currentIndexChanged(int index)
{
    initializeComponentCombo( ui->productComboBox->itemData(index).toInt() );
    initializeCategoryCombo( ui->productComboBox->itemData(index).toInt() );

    ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(noError());
}

void TaskEditDialog::on_componentComboBox_currentIndexChanged(int index)
{
    ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(noError());
}

void TaskEditDialog::on_categoryComboBox_currentIndexChanged(int index)
{
    ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(noError());
}

void TaskEditDialog::on_startEdit_dateTimeChanged(const QDateTime &date)
{
    if (date >= ui->endEdit->dateTime()) {
        ui->startEdit->setStyleSheet("background-color:#ff7070");
        ui->endEdit->setStyleSheet("background-color:#ff7070");
    }
    else {
        ui->startEdit->setStyleSheet("");
        ui->endEdit->setStyleSheet("");
    }
    ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(noError());
}

void TaskEditDialog::on_endEdit_dateTimeChanged(const QDateTime &date)
{
    if (date <= ui->startEdit->dateTime()) {
        ui->startEdit->setStyleSheet("background-color:#ff7070");
        ui->endEdit->setStyleSheet("background-color:#ff7070");
    }
    else {
        ui->startEdit->setStyleSheet("");
        ui->endEdit->setStyleSheet("");
    }
    ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(noError());
}

void TaskEditDialog::on_removeTaskButton_clicked()
{
    if (SqlHelper().deleteTask(db_, taskID_, this))
        done(Accepted);
}

bool TaskEditDialog::noError() const
{
    if (ui->productComboBox->currentIndex() == -1)
        return false;
    else if (ui->componentComboBox->currentIndex() == -1)
        return false;
    else if (ui->categoryComboBox->currentIndex() == -1)
        return false;
    else if (ui->startEdit->dateTime() >= ui->endEdit->dateTime())
        return false;
    else
        return true;
}
